//
//  ControlElement.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/5.
//

import UIKit

open class ControlElement: UIControl, FeedbackGeneratable {

    private(set) var currentState: State = .normal

    open override var isHighlighted: Bool {
        didSet {
            let newState: State = isHighlighted ? .highlighted : (isSelected ? .selected : .normal)
            setState(newState)
        }
    }

    open override var isEnabled: Bool {
        didSet {
            let newState: State = isEnabled ? (isSelected ? .selected : .normal) : .disabled
            setState(newState)
        }
    }
    
    open override var isSelected: Bool {
        didSet {
            let newState: State = isSelected ? .selected : .normal
            setState(newState)
        }
    }

    open var isFeedbackEnabled: Bool = true

    public override init(frame: CGRect) {
        super.init(frame: frame)
        setupFeedback()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFeedback()
    }

    final public func setState(_ newState: State) {
        currentState = newState
        stateDidChange()
    }

    open func stateDidChange() {
        
    }

    open func valueDidChange() {
        sendActions(for: .valueChanged)
    }

    private func setupFeedback() {
        addTarget(self, action: #selector(handleFeedbackIfNeeded), for: [.touchDown, .touchDragEnter])
    }

    @objc
    private func handleFeedbackIfNeeded() {
        guard isFeedbackEnabled else { return }
        generateSelectionFeedback()
    }

}

extension UIControl.State: Hashable {
    public var hashValue: Int {
        return Int((6777*self.rawValue+3777)%UInt(UInt16.max))
    }
}
